package com.yindian.cos.easy.security.authentication.login.social.qq;

import com.alibaba.fastjson.JSONObject;
import com.yindian.cos.easy.security.authentication.login.social.core.AbstractUserInfoFactory;
import com.yindian.cos.easy.security.authentication.login.social.core.AccessToken;
import com.yindian.cos.easy.security.constant.ProviderName;
import com.yindian.cos.easy.security.exception.UserInfoException;
import com.yindian.cos.easy.security.properties.EasySecurityProperties;
import com.yindian.cos.easy.security.properties.QqProperties;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.client.RestTemplate;

/**
 * qq获取UserInfo默认实现
 *
 * @author zhangchuanhao
 * @create 2018/11/20
 */
public class QqUserInfoFactory extends AbstractUserInfoFactory<QqUserInfo> {

    private EasySecurityProperties easySecurityProperties;

    private RestTemplate restTemplate;

    public QqUserInfoFactory(EasySecurityProperties easySecurityProperties, RestTemplate restTemplate) {
        this.easySecurityProperties = easySecurityProperties;
        this.restTemplate = restTemplate;
    }

    @Override
    public QqUserInfo getUserInfo(AccessToken accessToken) {
        try {
            String token = accessToken.getAccessToken();
            String openId = getOpenId(token);
            accessToken.setOpenId(openId);
            return getUserInfo(token, openId);
        } catch (UserInfoException ex) {
            throw ex;
        } catch (Exception ex) {
            throw new UserInfoException(ProviderName.QQ + "登录获取用户信息失败", ex.getCause());
        }
    }

    /**
     * 获取openId
     *
     * @param accessToken
     * @return
     */
    protected String getOpenId(String accessToken) {
        QqProperties qqProperties = easySecurityProperties.getQq();
        String url = qqProperties.getOpenIdUrl();
        url += "?access_token=" + accessToken;
        String result = restTemplate.getForObject(url, String.class);
        String openId;
        result = result.replace("callback(", "").replace(");", "");
        if (StringUtils.contains(result, "openid")) {
            openId = JSONObject.parseObject(result).getString("openid");
        } else {
            throw new UserInfoException(ProviderName.QQ + "登录获取open_id失败", result);
        }
        return openId;
    }

    /**
     * 获取用户信息
     *
     * @param accessToken
     * @param openId
     * @return
     */
    protected QqUserInfo getUserInfo(String accessToken, String openId) {
        QqProperties qqProperties = easySecurityProperties.getQq();
        String url = qqProperties.getUserInfoUrl();
        url += "?access_token=" + accessToken;
        url += "&oauth_consumer_key=" + qqProperties.getAppId();
        url += "&openid=" + openId;
        String result = restTemplate.getForObject(url, String.class);
        QqUserInfo userInfo = JSONObject.parseObject(result, QqUserInfo.class);
        return userInfo;
    }
}
